package l1j.william;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.serverpackets.S_NpcChatPacket;
import l1j.server.server.utils.SQLUtil;

public class NpcTalk {

	private static final Logger _log = Logger
			.getLogger(NpcTalk.class.getName());
	private final HashMap<Integer, L1NpcTalk> _talkList = new HashMap<Integer, L1NpcTalk>();
	private static NpcTalk _instance;

	public static NpcTalk getInstance() {
		if (_instance == null) {
			_instance = new NpcTalk();
		}
		return _instance;
	}

	public NpcTalk() {
		this.LoadData();
	}

	public void forL1MonsterTalking(L1NpcInstance monster) {
		final L1NpcTalk temp = this._talkList.get(monster.getNpcId());
		if (temp == null) {
			return;
		}
		int order = monster.getOrder();
		if (order > temp.getEnd()) {
			monster.setOrder(0);
			order = 0;
		}
		if (temp.getShout() != 0) {// TODO 大喊
			monster.broadcastPacketAll(new S_NpcChatPacket(monster, temp
					.getTalk(order), 2));
		} else {
			monster.broadcastPacketAll(new S_NpcChatPacket(monster, temp
					.getTalk(order), 0));
		}
		order++;
		monster.setOrder(order); // TODO 記錄目前的說話順序

	}

	private void LoadData() {
		Connection con = null;
		Statement stat = null;
		ResultSet rset = null;
		try {
			con = DatabaseFactory.get().getConnection();
			stat = con.createStatement();
			rset = stat.executeQuery("SELECT * FROM william_npc_talk");
			if (rset != null) {
				while (rset.next()) {
					final int npcid = rset.getInt("npc_id");
					L1NpcTalk aReturn = this._talkList.get(npcid);

					if (aReturn == null) {
						aReturn = new L1NpcTalk();
						aReturn.setShout(rset.getInt("shout"));
						aReturn.addTalk(rset.getInt("order"),
								rset.getString("talk"));
						aReturn.setEnd(rset.getInt("end"));
						this._talkList.put(npcid, aReturn);
					} else {
						aReturn.addTalk(rset.getInt("order"),
								rset.getString("talk"));
					}
				}
			}
		} catch (final Exception ex) {
			_log.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
		} finally {
			SQLUtil.close(rset, stat, con);
		}
	}
}